<?php

namespace app\common\controller;
use app\common\model\Member;
use app\common\library\Auth;
use app\common\model\Category;
use think\Config;
use think\Cookie;
use think\Controller;
use think\Hook;
use think\Lang;
use fast\Date;
/**
 * 前台控制器基类
 */
class Frontend extends Controller
{

    /**
     * 布局模板
     * @var string
     */
    protected $layout = '';

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    //权限Auth  @var Auth
    protected $auth = null;
    //快速搜索时执行查找的字段
    protected $searchFields = 'id';
    //是否是关联查询
    protected $relationSearch = false;
    protected $columnarry = array();
    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;
    //数据限制字段
    protected $dataLimitField = 'admin_id';
    //是否开启Validate验证
    protected $modelValidate = false;
    //是否开启模型场景验证
    protected $modelSceneValidate = false;
    //Multi方法可批量修改的字段/
    protected $multiFields = 'status';
    public function _initialize()
    {
        //移除HTML标签
        $this->request->filter('strip_tags');
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        // 如果有使用模板布局
        if ($this->layout){
            $this->view->engine->layout('layout/' . $this->layout);
        }
        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin))
        {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()){
                $this->error(__('Please login first'), 'user/login');
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight))
            {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path))
                {
                    $this->error(__('You have no permission'));
                }
            }
        }
        else
        {
            // 如果有传递token才验证是否登录状态
            if ($token)
            {
                $this->auth->init($token);
            }
        }

        $this->view->assign('user', $this->auth->getUser());
        $uid = Cookie::get('uid');
        //print_r($uid);exit;
        if($uid){
            $this->view->assign('member',Member::get($uid));
        }else{
            $this->view->assign('member',array());
        }
        $this->view->assign('memberid', Cookie::get('uid')?Cookie::get('uid'):'');
        // 语言检测
        $lang = strip_tags(Lang::detect());

        $site = Config::get("site");
        $upload = \app\common\model\Config::upload();
        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);
        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'frontend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang
        ];
        $config = array_merge($config, Config::get("view_replace_str"));
        Config::set('upload', array_merge(Config::get('upload'), $upload));
        // 配置信息后
        Hook::listen("config_init", $config);
        // 加载当前控制器语言包
        $this->loadlang($controllername);
        //创建导航pid = 14 and `status`='normal';
        $condition = array();
        $condition['pid'] = 14;
        $condition['status'] = 'normal';
        $listcategory = model('Category')->where($condition)->order('weigh','desc')->select();
        $this->assign('navlist',$listcategory);
        //当前时间
        $this->assign('date',date('Y-m-d H:i:s',time()));
        $this->assign('site', $site);
        $this->assign('config', $config);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed $searchfields 快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @param mixed $searchdefault 默认的查询字段
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null,$searchdefault = null){
        //搜索用到的列
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        //请求的列值
        $searchform = $this->request->get("search/a");
        $search = array();
        if($searchform){
            if($searchdefault){
                $search = array_merge($searchdefault,$searchform);
            }else{
                $search = $searchform;
            }
        }else{
            $search = $searchdefault;
        }
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        //排序字段
        $sort = $this->request->get("sort", "itemid");
        //DESC倒序--ASC正序
        $order = $this->request->get("order", "DESC");
        //起始值
        $offset = $this->request->get("offset",0);
        //每页显示多少条
        $limit = $this->request->get("limit",10);
        $filter = json_decode($filter, TRUE);
        $op = json_decode($op, TRUE);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch){
            if (!empty($this->model)){
                $class = get_class($this->model);
                $name = basename(str_replace('\\', '/', $class));
                $tableName = $this->model->getQuery()->getTable($name) . ".";
            }
            $sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)){
            $where[] = [$this->dataLimitField, 'in', $adminIds];
        }
    		$searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
    		foreach ($searcharr as $k => &$v){
            if(isset($search[$k])){
                if(($v=='varcharmid')||($v=='varcharshort')||($v=='varcharlong')){
                    $where[] = [$k, "LIKE", "%".$search[$k]."%"];
                }else{
                    $where[] = [$k, $search[$k]];
                }
            }
            $this->view->assign($k,isset($search[$k])?$search[$k]:'');
    		}
    		unset($v);
        //if ($search){}
        foreach ($filter as $k => $v){
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false){
                $k = $tableName . $k;
            }
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym){
                case '=':
                case '!=':
                    $where[] = [$k, $sym, (string) $v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '')
                    {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    }
                    else if ($arr[1] === '')
                    {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '')
                    {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    }
                    else if ($arr[1] === '')
                    {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        //print_r($where);exit;
        $where = function($query) use ($where) {
            foreach ($where as $k => $v){
                if (is_array($v)){
                    call_user_func_array([$query, 'where'], $v);
                }
                else{
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }
    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 渲染配置信息
     * @param mixed $name 键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }
    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds(){
        if (!$this->dataLimit){
            return null;
        }
        $adminIds = [];
        if (in_array($this->dataLimit, ['auth', 'personal']))
        {
            $adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
        }
        return $adminIds;
    }
}
